const axios = require('axios')
const {
    clientID,
    clientSecret,
    weiboID,
    weiboSecret
} = require('../config/default')
const userModel = require('../lib/mysql.js')
const md5 = require('md5')
const moment = require('moment');
const {
    setToken
} = require('../middlewares/token_verify')

//github授权登录
exports.oauth = async ctx => {
    try {
        const requestToken = ctx.request.query.code;
        const tokenResponse = await axios({
            method: 'post',
            url: 'https://github.com/login/oauth/access_token?' +
                `client_id=${clientID}&` +
                `client_secret=${clientSecret}&` +
                `code=${requestToken}`,
            headers: {
                accept: 'application/json'
            }
        });
        const accessToken = tokenResponse.data.access_token;
        console.log(accessToken)
        const result = await axios({
            method: 'get',
            url: `https://api.github.com/user`,
            headers: {
                accept: 'application/json',
                Authorization: `token ${accessToken}`
            }
        });
        console.log(result.data)
        let {
            id,
            name,
            login,
            avatar_url
        } = result.data
        await userModel.findDataCountByGithubId(id)
            .then(async (result) => {
                if (result[0].count >= 1) {
                    // 用户存在
                    console.log('用户存在')
                    let res = await userModel.findDataBygithubId(id)
                    setToken(name, res[0]['id']).then(token => {
                        ctx.response.redirect('http://www.keledd.cn:8081/redirect?token=' + token + '&&id=' + id);
                    })
                } else {
                    console.log('用户不存在')
                    await userModel.insertDatabyThird([avatar_url, moment().format('YYYY-MM-DD HH:mm:ss'), id])
                    let res = await userModel.findDataBygithubId(id)
                    await userModel.insertThirdData([id, 'github', name, res[0]['id'], avatar_url])
                    setToken(name, res[0]['id']).then(token => {
                        ctx.response.redirect('http://www.keledd.cn:8081/redirect?token=' + token + '&&id=' + id);
                    })
                }
            })

    } catch (e) {
        console.log(e)
    }

}
//授权登录请求
exports.githubLogin = async ctx => {
    let {
        id
    } = ctx.request.body
    await userModel.findDataCountByGithubId(id)
        .then(res => {
            if (res[0].count <= 0) {
                ctx.body = {
                    code: 401,
                    message: '登录出错，请重新授权',
                }
            }
        })
    let thirdInfo = await userModel.findThirdBygithubId(id)
    console.log(thirdInfo)
    setToken(thirdInfo[0]['name'], thirdInfo[0]['userid']).then(token => {
        ctx.body = {
            code: 200,
            message: '登录成功',
            userInfo: {
                user: thirdInfo[0]['name'],
                id: thirdInfo[0]['userid'],
                avatar: thirdInfo[0]['avatar'],
                token: token
            }
        }
    })
}


//weibo授权登录
exports.weiboOauth = async ctx => {
    try {
        let requestToken = ctx.request.query.code;
        let tokenResponse = await axios({
            method: 'post',
            url: 'https://api.weibo.com/oauth2/access_token?' +
                `client_id=${weiboID}&` +
                `client_secret=${weiboSecret}&grant_type=authorization_code&redirect_uri=http://www.keledd.cn:3000/oauth/weibo&` +
                `code=${requestToken}`,
            headers: {
                accept: 'application/json'
            }
        });
        let accessToken = tokenResponse.data.access_token;
        let uid = tokenResponse.data.uid;
        console.log(accessToken)
        let result = await axios({
            method: 'get',
            url: `https://api.weibo.com/2/users/show.json?access_token=${accessToken}&uid=${uid}`,
            headers: {
                accept: 'application/json',
            }
        });
        console.log(result.data)
        let {
            id,
            name,
            avatar_large
        } = result.data
        await userModel.findDataCountByweiboId(id)
            .then(async (result) => {
                if (result[0].count >= 1) {
                    // 用户存在
                    console.log('用户存在')
                    let res = await userModel.findDataByweiboId(id)
                    setToken(name, res[0]['id']).then(token => {
                        ctx.response.redirect(`http://www.keledd.cn:8080/redirect?token=${token}&&id=${id}&&type=weibo`);
                    })
                } else {
                    console.log('用户不存在')
                    // 第三方插入主表
                    await userModel.insertDatabyweibo([avatar_large, moment().format('YYYY-MM-DD HH:mm:ss'), id])
                    let res = await userModel.findDataByweiboId(id)
                    await userModel.insertThirdData([id, 'weibo', name, res[0]['id'], avatar_large])
                    setToken(name, res[0]['id']).then(token => {
                        ctx.response.redirect(`http://www.keledd.cn:8080/redirect?token=${token}&&id=${id}&&type=weibo`);
                    })
                }
            })

    } catch (e) {
        console.log(e)
    }

}
//根据微博id授权登录请求
exports.weiboLogin = async ctx => {
    let {
        id
    } = ctx.request.body
    await userModel.findDataCountByweiboId(id)
        .then(res => {
            if (res[0].count <= 0) {
                ctx.body = {
                    code: 401,
                    message: '登录出错，请重新授权',
                }
            }
        })
    let thirdInfo = await userModel.findThirdByweiboId(id)
    console.log(thirdInfo)
    setToken(thirdInfo[0]['name'], thirdInfo[0]['userid']).then(token => {
        ctx.body = {
            code: 200,
            message: '登录成功',
            userInfo: {
                user: thirdInfo[0]['name'],
                id: thirdInfo[0]['userid'],
                avatar: thirdInfo[0]['avatar'],
                token: token
            }
        }
    })
}